package com.che.software.testato.business;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.che.software.testato.business.exception.IterationCreationManagerException;
import com.che.software.testato.business.exception.IterationSearchManagerException;
import com.che.software.testato.business.exception.IterationUpdateManagerException;
import com.che.software.testato.domain.dao.IIterationDAO;
import com.che.software.testato.domain.dao.IPrioritizationDAO;
import com.che.software.testato.domain.dao.IScriptDAO;
import com.che.software.testato.domain.dao.IScriptItemDAO;
import com.che.software.testato.domain.dao.jdbc.exception.IterationSearchDAOException;
import com.che.software.testato.domain.dao.jdbc.exception.IterationUpdateDAOException;
import com.che.software.testato.domain.entity.Iteration;
import com.che.software.testato.domain.entity.Prioritization;
import com.che.software.testato.domain.entity.Script;
import com.che.software.testato.domain.entity.ScriptItem;
import com.che.software.testato.domain.entity.search.IterationSearch;
import com.che.software.testato.domain.entity.search.PrioritizationSearch;
import com.che.software.testato.domain.entity.search.ScriptItemSearch;
import com.che.software.testato.domain.entity.search.ScriptSearch;
import com.che.software.testato.domain.enumeration.AssignmentStatus;

/**
 * Manager dedicated to the iterations.
 * 
 * @author Clement HELIOU (clement.heliou@che-software.com).
 * @copyright Che Software.
 * @license GNU General Public License.
 * @since July, 2011.
 * 
 * This file is part of Testato.
 * 
 * Testato is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 * 
 * Testato is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with Testato. If not, see <http://www.gnu.org/licenses/>.
 * 
 * Testato's logo is a creation of Arrioch (http://arrioch.deviantart.com/) and it's distributed under the terms of the Creative Commons License.
 */
@Service("iterationManager")
public class IterationManager {

	/**
	 * Constants.
	 */
	private static final Logger LOGGER = Logger.getLogger(IterationManager.class);

	/**
	 * Members.
	 */
	@Autowired
	private IIterationDAO iterationDAO;
	@Autowired
	private IPrioritizationDAO prioritizationDAO;
	@Autowired
	private IScriptDAO scriptDAO;
	@Autowired
	private IScriptItemDAO scriptItemDAO;

	/**
	 * Creates the next iteration (both analytical and selective) for a given prioritization.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param prioritization the given prioritization.
	 * @param parentItemId the parent item id. Null if we are looking for the first level
	 * @return true if an iteration has been created or if the current iteration is not completed yet, else false.
	 * @since July, 2011.
	 * @throws IterationCreationManagerException if an error occurs during the creation.
	 */
	public boolean createNextIteration(Prioritization prioritization, Integer parentItemId) throws IterationCreationManagerException {
		LOGGER.debug("createNextIteration(" + prioritization.getHierarchyId() + ").");
		ScriptSearch searchBean = new ScriptSearch(prioritization.getHierarchyId());
		searchBean.setParentScriptItem((null != parentItemId) ? parentItemId : 0);
		try {
			List<Script> scripts = scriptDAO.searchScript(searchBean);
			if (null != scripts && !scripts.isEmpty()) {
				IterationSearch iterationSearchBean = new IterationSearch();
				iterationSearchBean.setScriptId(scripts.get(0).getScriptId());
				List<Iteration> iterations = iterationDAO.searchIteration(iterationSearchBean);
				if (null == iterations || iterations.isEmpty()) {
					iterationDAO.createNextIteration(prioritization, scripts);
					LOGGER.debug("Stop condition: iteration created!");
					return true;
				}
				if (!isIterationCompleted(iterations.get(0).getIterationId())) {
					LOGGER.debug("Stop condition: iteration not completed yet!");
					return false;
				}
				searchBean = new ScriptSearch(prioritization.getHierarchyId());
				searchBean.setIterationId(iterations.get(0).getIterationId());
				searchBean.setSelected(false);
				scripts.removeAll(scriptDAO.searchScript(searchBean));
				for (Script script : scripts) {
					ScriptItemSearch scriptItemSearchBean = new ScriptItemSearch();
					scriptItemSearchBean.setScriptId(script.getScriptId());
					for (ScriptItem item : scriptItemDAO.searchScriptItem(scriptItemSearchBean)) {
						if (createNextIteration(prioritization, item.getScriptItemId())) {
							return true;
						}
					}
				}
			}
			LOGGER.debug("Stop condition: all iterations have bean created!");
			return false;
		}
		catch (Exception e) {
			throw new IterationCreationManagerException(e);
		}
	}

	/**
	 * Retrieves the current iteration to process for a given hierarchy.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param hierarchyId the given hierarchy id.
	 * @return the current iteration to process id.
	 * @since July, 2011.
	 * @throws IterationSearchDAOException if an error occurs during the search.
	 */
	public int getCurrentIterationFromHierarchy(int hierarchyId) throws IterationSearchManagerException {
		LOGGER.debug("getCurrentIterationFromHierarchy(" + hierarchyId + ").");
		try {
			return iterationDAO.getCurrentIterationFromPrioritization(prioritizationDAO.searchPrioritization(new PrioritizationSearch(hierarchyId)).get(0));
		}
		catch (Exception e) {
			throw new IterationSearchManagerException(e);
		}
	}

	/**
	 * Retrieves the remaining scripts count for given prioritization and item.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param prioritization the given prioritization.
	 * @param parentItemId the parent item id. Null if we are looking for the first level
	 * @return the resulting count.
	 * @since July, 2011.
	 * @throws IterationSearchManagerException if an error occurs during the search.
	 */
	public int getRemainingScriptsCountFromPrioritization(Prioritization prioritization, Integer parentItemId) throws IterationSearchManagerException {
		LOGGER.debug("getRemainingScriptsCountFromPrioritization(" + prioritization.getHierarchyId() + "," + parentItemId + ").");
		int count = 0;
		ScriptSearch searchBean = new ScriptSearch(prioritization.getHierarchyId());
		searchBean.setParentScriptItem((null != parentItemId) ? parentItemId : 0);
		try {
			List<Script> scripts = scriptDAO.searchScript(searchBean);
			if (null != scripts && !scripts.isEmpty()) {
				IterationSearch iterationSearchBean = new IterationSearch();
				iterationSearchBean.setScriptId(scripts.get(0).getScriptId());
				List<Iteration> iterations = iterationDAO.searchIteration(iterationSearchBean);
				if (null == iterations || iterations.isEmpty()) {
					count++;
				}
				else {
					searchBean = new ScriptSearch(prioritization.getHierarchyId());
					searchBean.setIterationId(iterations.get(0).getIterationId());
					searchBean.setSelected(false);
					scripts.removeAll(scriptDAO.searchScript(searchBean));
				}
				for (Script script : scripts) {
					ScriptItemSearch scriptItemSearchBean = new ScriptItemSearch();
					scriptItemSearchBean.setScriptId(script.getScriptId());
					for (ScriptItem item : scriptItemDAO.searchScriptItem(scriptItemSearchBean)) {
						count += getRemainingScriptsCountFromPrioritization(prioritization, item.getScriptItemId());
					}
				}
			}
		}
		catch (Exception e) {
			LOGGER.error("Error during the remaining scripts counting from current prioritization.", e);
		}
		return count;
	}

	/**
	 * Retrieves the scripts count for a given iteration.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param iterationId the given iteration id.
	 * @return the resulting scripts count.
	 * @since July, 2011.
	 * @throws IterationSearchManagerException if an error occurs during a search.
	 */
	public int getScriptsCountFromIteration(int iterationId) throws IterationSearchManagerException {
		LOGGER.debug("getScriptsCountFromIteration(" + iterationId + ").");
		try {
			return iterationDAO.getScriptsCountFromIteration(iterationId);
		}
		catch (IterationSearchDAOException e) {
			throw new IterationSearchManagerException(e);
		}
	}

	/**
	 * Checks if an iteration is completed. In other words, checks if the selective prioritization has been completed for the given iteration.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param iterationId the given iteration id.
	 * @return true if the iteration is ended, else false.
	 * @since August, 2011.
	 * @throws IterationSearchManagerException if an error occurs during the search.
	 */
	public boolean isIterationCompleted(int iterationId) throws IterationSearchManagerException {
		LOGGER.debug("isIterationCompleted(" + iterationId + ").");
		IterationSearch searchBean = new IterationSearch();
		searchBean.setIterationId(iterationId);
		searchBean.setSelectiveStatus(AssignmentStatus.ENDED);
		try {
			List<Iteration> iterations = iterationDAO.searchIteration(searchBean);
			return null != iterations && !iterations.isEmpty();
		}
		catch (IterationSearchDAOException e) {
			throw new IterationSearchManagerException(e);
		}
	}

	/**
	 * Checks if an iteration assignment is completed. In other words, checks if the related comparison matrix has been prioritized.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param iterationAssignmentId the given iteration assignment id.
	 * @return true if the iteration assignment is ended, else false.
	 * @since August, 2011.
	 * @throws IterationSearchManagerException if an error occurs during the search.
	 */
	public boolean isIterationAssignmentCompleted(int iterationAssignmentId) throws IterationSearchManagerException {
		LOGGER.debug("isIterationCompleted(" + iterationAssignmentId + ").");
		try {
			return iterationDAO.isIterationCompleted(iterationAssignmentId);
		}
		catch (IterationSearchDAOException e) {
			throw new IterationSearchManagerException(e);
		}
	}

	/**
	 * Iteration search from a bean of criterions.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param searchBean the criterions to use for the search.
	 * @return the resulting object list.
	 * @since July, 2011.
	 * @throws IterationSearchManagerException if an error occurs during the search.
	 */
	public List<Iteration> searchIteration(IterationSearch searchBean) throws IterationSearchManagerException {
		LOGGER.debug("searchIteration().");
		try {
			return iterationDAO.searchIteration(searchBean);
		}
		catch (IterationSearchDAOException e) {
			throw new IterationSearchManagerException(e);
		}
	}

	/**
	 * Updates an iteration from his object.
	 * 
	 * @author Clement HELIOU (clement.heliou@che-software.com).
	 * @param iterationToUpdate the iteration object to update in the database.
	 * @since July, 2011.
	 * @throws IterationUpdateManagerException if an error occurs during the update.
	 */
	public void updateIteration(Iteration iterationToUpdate) throws IterationUpdateManagerException {
		LOGGER.debug("updateIteration(" + iterationToUpdate.getIterationAssignmentId() + ").");
		try {
			iterationDAO.updateIteration(iterationToUpdate);
		}
		catch (IterationUpdateDAOException e) {
			throw new IterationUpdateManagerException(e);
		}
	}

	/**
	 * Getter for the private field value iterationDAO.
	 * 
	 * @return the iterationDAO field value.
	 */
	public IIterationDAO getIterationDAO() {
		return iterationDAO;
	}

	/**
	 * Setting a value to the iterationDAO field.
	 * 
	 * @param iterationDAO the value to set.
	 */
	public void setIterationDAO(IIterationDAO iterationDAO) {
		this.iterationDAO = iterationDAO;
	}

	/**
	 * Getter for the private field value scriptDAO.
	 * 
	 * @return the scriptDAO field value.
	 */
	public IScriptDAO getScriptDAO() {
		return scriptDAO;
	}

	/**
	 * Setting a value to the scriptDAO field.
	 * 
	 * @param scriptDAO the value to set.
	 */
	public void setScriptDAO(IScriptDAO scriptDAO) {
		this.scriptDAO = scriptDAO;
	}

	/**
	 * Getter for the private field value prioritizationDAO.
	 * 
	 * @return the prioritizationDAO field value.
	 */
	public IPrioritizationDAO getPrioritizationDAO() {
		return prioritizationDAO;
	}

	/**
	 * Setting a value to the prioritizationDAO field.
	 * 
	 * @param prioritizationDAO the value to set.
	 */
	public void setPrioritizationDAO(IPrioritizationDAO prioritizationDAO) {
		this.prioritizationDAO = prioritizationDAO;
	}

	/**
	 * Getter for the private field value scriptItemDAO.
	 * 
	 * @return the scriptItemDAO field value.
	 */
	public IScriptItemDAO getScriptItemDAO() {
		return scriptItemDAO;
	}

	/**
	 * Setting a value to the scriptItemDAO field.
	 * 
	 * @param scriptItemDAO the value to set.
	 */
	public void setScriptItemDAO(IScriptItemDAO scriptItemDAO) {
		this.scriptItemDAO = scriptItemDAO;
	}
}